package com.jumi.microservice.redissetnx;

import com.jumi.microservice.common.exception.BaseException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author by mazhao
 * @Classname TaskAspect
 * @Description TODO
 * @Date 2020/10/16 10:10
 */

@Aspect
@Component
public class CpsTaskAspect {

    @Value("${spring.application.name}")
    private String projectName;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Around("execution(* com.jumi.microservice..*.*(..)) && @annotation(org.springframework.scheduling.annotation.Scheduled)")
    public Object task(ProceedingJoinPoint point) {
        String key = projectName+"::"+point.getSignature().getName();
        Boolean result = redisTemplate.opsForValue().setIfAbsent(key, "", 50, TimeUnit.SECONDS);
        if(result != null && result) {
            try {
                return point.proceed();
            } catch (Throwable e) {
                redisTemplate.delete(key);
                throw new BaseException(500,"定时任务出错 :"+e.getMessage());
            }
        }
        return null;
    }

}
